<template>
	<uni-nav-bar
	  dark 
	  :fixed="true" 
	  shadow 
	  status-bar 
	  left-icon="arrow-left" 
	  :title=title
	  @clickLeft="back" 
	/>
  <view class="container">
	  <!-- 导航栏 -->
	 
	  
    <!-- 顶部固定区域 -->
    <view class="fixed-top" >
      <!-- 顶部标签栏 -->
      <!-- <view class="tab-bar" >
        <view
          v-for="t in tabs"
          :key="t.key"
          class="tab"
          :class="{ active: activeTab === t.key }"
          @tap="switchTab(t.key)"
        >
          {{ t.name }}
        </view>
      </view> -->

      <!-- 日期栏 -->
      <view class="date-bar">
        <text class="left">{{ titleText }}专业欠费(万元)</text>
        <text class="date">{{ todayText }}</text>
        <button class="history-btn" @tap="openDatePicker">查看历史</button>
      </view>

      <!-- 日 / 月 / 跨赛 -->
     <!-- <view class="period-bar">
        <view
          v-for="p in periods"
          :key="p.key"
          class="period"
          :class="{ active: activePeriod === p.key }"
          @tap="switchPeriod(p.key)"
        >
          {{ p.name }}
        </view>
      </view> -->

      <!-- 表头 -->
      <view class="table-header" >
        <view class="fixed-left-header" >
          <view class="tr head">
            <view class="th rank">排名</view>
            <view class="th city">{{ dimensionName }}</view>
          </view>
        </view>

        <scroll-view
          scroll-x
          :scroll-left="scrollLeft"
          class="scroll-right-header" 
        >
          <view class="tr head" >
            <view
              v-for="col in columns"
              :key="col.key"
              class="th sort-th"
              @tap="sortBy(col.key)"
            >
              {{ col.name }}
              <view class="arrows">
                <text
                  class="up"
                  :class="{ active: sortKey === col.key && sortOrder === 'asc' }"
                >▲</text>
                <text
                  class="down"
                  :class="{ active: sortKey === col.key && sortOrder === 'desc' }"
                >▼</text>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
    <!-- 内容区：上下滚动时整行联动 -->
    <scroll-view scroll-y class="scroll-y-wrapper">
      <view class="table-body">
        <!-- 左侧固定列 -->
        <view class="fixed-left">
          <view
            v-for="(item, index) in rowHeightList"
            :key="item.code"
            class="tr"
            :class="[item.heightCls, { stripe: index % 2 === 1 }]"

          >
            <view class="td rank">
              <text 
			  :class="{
			    'rank-box': activeTab === 'county',
			    'black-text': activeTab === 'branch'
			  }"
			  >{{ index + 1 }}</text>
            </view>
            <view
              class="td city"
              :class="{ 
                'red-text': activeTab === 'county',
                'black-text': activeTab === 'branch'
              }"
              @tap="countyClick(item)"
            >
              <text
                class="city-text"
                :jb="jb"
              >
                {{ item.name }}
              </text>
            </view>
          </view>
          
        </view>
        <!-- 右侧可横向滚动的内容 -->
        <scroll-view
          scroll-x
          scroll-y
          @scroll="onRightScroll"
          class="scroll-right-body"
        >
          <view class="table-data">
            <view
              v-for="(item, index) in rowHeightList"
              :key="item.code"
              class="tr"
              :class="[item.heightCls, { stripe: index % 2 === 1 }]"
            >
              <view class="td">{{ item.hj }}</view>
              <view class="td">{{ item.yqqf }}</view>
            </view>
			

          </view>
        </scroll-view>
      </view>
    </scroll-view>
	<view style="height: 88rpx;"></view>
	<!-- 原来合计行删掉，换成下面这一段（放到最外层，和 scroll-y-wrapper 同级） -->
<view class="total-row">
  <!-- 左侧固定 -->
  <view class="total-left">
    <view class="td">-</view>
    <view class="td">合计</view>
  </view>

  <!-- 右侧可滚动 -->
  <scroll-view
    scroll-x
    class="total-right"
    :scroll-left="scrollLeft"
  >
    <view class="total-data">
      <view
        v-for="col in columns"
        :key="col.key"
        class="td-mx"
      >
        {{ total[col.key] }}
      </view>
    </view>
  </scroll-view>
</view>

    <!-- 三级联动日期弹窗 -->
    <view v-if="showPicker" class="mask" @tap="showPicker=false">
      <view class="picker-panel" @tap.stop>
        <picker-view
          :value="pickerVal"
          indicator-style="height:88rpx"
          style="height:420rpx"
          @change="pickerChange"
        >
          <picker-view-column>
            <view v-for="(y,i) in years" :key="i" class="picker-item">{{ y }}年</view>
          </picker-view-column>
          <picker-view-column>
            <view v-for="(m,i) in months" :key="i" class="picker-item">{{ m }}月</view>
          </picker-view-column>
          <picker-view-column>
            <view v-for="(d,i) in days" :key="i" class="picker-item">{{ d }}日</view>
          </picker-view-column>
        </picker-view>
        <view class="btn-group">
          <text class="btn" @tap="showPicker=false">取消</text>
          <text class="btn confirm" @tap="confirmDate">确定</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import utils from '../../common/utils'
import store from '../../common/store.js'
export default {
  data() {
    return {
		title:"专业看板",
      activeTab   : 'county',
      tabs        : [
        { key: 'county', name: '县市' },
        { key: 'branch', name: '网点' }
      ],
	  cachedTotal: null, // 缓存上级合计
	  cachedTotal2: null, // 缓存上级合计
	  cachedTotal3: null, // 缓存上级合计
      activePeriod: 'day',
      periods     : [
        { key: 'day',    name: '日' },
        { key: 'month',  name: '月' },
        { key: 'season', name: '跨赛' }
      ],
      columns: [
        { key: 'hj',  name: '欠费总计' },
        { key: 'yqqf',  name: '逾期欠费' }
      ],
      list     : [],
      total    : {},
      sortKey  : '',
      sortOrder: '',
      todayText: '',
      queryDate: '',
      showPicker: false,
      pickerVal: [0,0,0],
      years : [],
      months: [],
      days  : [],
	  pcode:"",
	  zy:'',
      scrollLeft: 0,
	  jb:"1",
	  jb2code:''
    }
  },
  computed: {
    dimensionName() {
		if(this.jb=='1'){
			return '专业';
		}
		if(this.jb=='2'||this.jb=='3'){
			return '机构';
		}
		if(this.jb=='4'){
			return '客户';
		}
		
    },
    showList() {
	  
      if (!this.sortKey) return this.list
      const arr = [...this.list]
      const key = this.sortKey, order = this.sortOrder
      arr.sort((a, b) =>
        order === 'asc'
          ? Number(a[key]) - Number(b[key])
          : Number(b[key]) - Number(a[key])
      )
      return arr
    },
	rowHeightList(){
	  return this.showList.map(item=>{
	    const len = item.name.length
	    let cls = 'h80'
	    if (len > 25) cls = 'h240'
	    else if (len > 20) cls = 'h200'
	    else if (len > 15) cls = 'h160'
	    else if (len > 10) cls = 'h120'
	    else if (len > 5) cls = 'h80'
	    return { ...item, heightCls: cls }
	  })
	}
  }, 
  onLoad() {
    this.initDate()
    this.loadData(this.jb)
  },
  methods: { 
	  countyClick(item) {
	    if (this.jb === "1") {
	      this.zy = item.name;
	      this.title = "专业看板(" + item.name + ")";
	      this.jb = "2";
	      this.activeTab = "county";
	  
	      this.cachedTotal = { hj: item.hj, yqqf: item.yqqf }; // ✅ 缓存第二级
	      this.loadData(this.jb);
	  
	    } else if (this.jb === "2") {
	      this.pcode = item.code;
		  this.jb2code=item.code;
	      this.jb = "3";
	      this.activeTab = "county";
	  
	      this.cachedTotal2 = { hj: item.hj, yqqf: item.yqqf }; // ✅ 缓存第三级
	      this.loadData(this.jb);
	    } else if (this.jb === "3") {
			console.info("item:"+JSON.stringify(item));
	      this.pcode = item.jg;
	      this.jb = "4";
	      this.activeTab = "branch";
	  
	      this.cachedTotal3 = { hj: item.hj, yqqf: item.yqqf }; // ✅ 缓存第四级
	      this.loadData(this.jb);
	    }
	  },
    initDate() {
      const today = new Date()
      this.initPicker(today)  
      this.setToday(today) 
    }, 
    setToday(date) {
      const y = date.getFullYear()
      const m = (date.getMonth() + 1).toString().padStart(2, '0')
      const d = date.getDate().toString().padStart(2, '0')
      this.todayText = `${y}年${m}月${d}日`
      this.queryDate = `${y}-${m}-${d}`
    },
    initPicker(date) {
      const y = date.getFullYear()
      const m = date.getMonth() + 1
      const d = date.getDate()
      this.years  = Array.from({ length: 11 }, (_, i) => y - 5 + i)
      this.months = Array.from({ length: 12 }, (_, i) => i + 1)
      this.updateDays(y, m)
      this.pickerVal = [
        this.years.indexOf(y),
        m - 1,
        d - 1
      ]
    },
    updateDays(y, m) {
      const max = new Date(y, m, 0).getDate()
      this.days = Array.from({ length: max }, (_, i) => i + 1)
    },
    pickerChange(e) {
      const [yi, mi, di] = e.detail.value
      const y = this.years[yi]
      const m = this.months[mi]
      if (mi !== this.pickerVal[1]) {
        this.updateDays(y, m)
      }
      this.pickerVal = [yi, mi, Math.min(di, this.days.length - 1)]
    },
    openDatePicker() {
      const [y, m, d] = this.queryDate.split('-').map(Number)
      this.initPicker(new Date(y, m - 1, d))
      this.showPicker = true
    },
    confirmDate() {
      const [yi, mi, di] = this.pickerVal
      const date = new Date(this.years[yi], this.months[mi] - 1, this.days[di])
      this.setToday(date)
      this.showPicker = false
      this.loadData(this.jb)
    },
    sortBy(key) {
      if (this.sortKey === key) {
        if (this.sortOrder === '')         this.sortOrder = 'asc'
        else if (this.sortOrder === 'asc') this.sortOrder = 'desc'
        else { this.sortKey = ''; this.sortOrder = '' }
      } else {
        this.sortKey = key
        this.sortOrder = 'asc'
      }
    },
    onRightScroll(e) {
      this.scrollLeft = e.detail.scrollLeft
    },
	chineseDateToYmd(str) {
	  // 2025年08月25日 → 2025-08-25
	  return str
	    .replace(/年|月/g, '-')
	    .replace(/日/g, '')
	    .replace(/-(\d)(?=-|$)/g, '-0$1'); // 补零
	},
	back() {
	  if (this.jb === '1') {
	    uni.navigateBack();
	  } else if (this.jb === '2') {
	    this.jb = '1';
	    this.activeTab = "county";
	    this.cachedTotal = null;
	    this.title = "专业看板";
	    this.loadData(this.jb);
	  } else if (this.jb === '3') {
	    this.jb = '2';
	    this.activeTab = "branch";
	    this.title = "专业看板(" + this.zy + ")";
		this.pcode="";
	    this.loadData(this.jb);
	  }
	  else if (this.jb === '4') {
	    this.jb = '3';
	    this.activeTab = "branch";
	    this.title = "专业看板(" + this.zy + ")";
	  	this.pcode=this.jb2code;
	    this.loadData(this.jb);
	  }
	},
    loadData: async function (jb) {
		this.list=[]
      this.$utils.showLoading('数据加载中...')
      let data = {
        timestamp: this.$utils.getTimestamp(),
		jb:jb,
		zy:this.zy,
		pcode:this.pcode,
        rq:this.chineseDateToYmd(this.todayText)
		// rq:'2025-08-20', 
      }
      let enData = this.$utils.encrypt(JSON.stringify(data), uni.getStorageSync("userInfo").aesKey, uni.getStorageSync("userInfo").aesIv)
      let postData = { data: '' + enData + '' }
      try {
        let res = await this.$myRequest.post_token('qyh/qfkb/zykbInitData', postData)
        if (res.code === 200) {
          let a = JSON.parse(utils.decrypt(res.data, uni.getStorageSync("userInfo").aesKey, uni.getStorageSync("userInfo").aesIv))
          console.log("a:"+JSON.stringify(a)); 
		  const src = a.zyqfList || []
		   
		  console.log("src:"+JSON.stringify(src)); 
          this.list = src.map((row, idx) => ({
            name        : row.name.replace("中国邮政集团有限公司","").replace("武汉市",""),
            rank        : idx + 1,
			code		: row.pcode,
            hj  : this.formatToWan(row.hj),  
            yqqf  : this.formatToWan(row.yqqf) ,
			jg			:row.jg
          }))
          if (jb =="1") {
			  // ✅ 只有第一级才重新计算合计
			  const t = { hj: 0, yqqf: 0 };
			  this.list.forEach(r => {
			    t.hj += Number(r.hj);
			    t.yqqf += Number(r.yqqf);
			  });
			  Object.keys(t).forEach(k => (t[k] = t[k].toFixed(2)));
			  this.total = t;
             
          } else if(jb=="2") {
           // ✅ 用缓存的合计，避免四舍五入不一致
             this.total = this.cachedTotal;
          }else if(jb=="3") {
			  this.total = this.cachedTotal2;
		  }else if(jb=="4") {
			  this.total = this.cachedTotal3;
		  }
        } else {
          this.$utils.toast(res.msg || '数据加载失败')
        }
      } catch (e) {
        this.$utils.toast('网络异常：' + e)
      } finally {
        this.$utils.hideLoading()
      }
    },
	//返回万元
	formatToWan(num){
		return this.$utils.formatToWan(num);
	}
  }
}
</script>

<style lang="scss" scoped>
/* ===== 全局容器 ===== */
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f6f6f6;
  flex: 1;            /* 占剩余高度 */
}

/* ===== 顶部固定区域 ===== */
.fixed-top {
  // position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background: #f6f6f6;
  flex-shrink: 0;         /* 不被压缩 */
  
}

/* 标签栏 */
.tab-bar {
  display: flex;
  background: #fff;
  border-bottom: 1rpx solid #e8e8e8;
  .tab {
    flex: 1;
    text-align: center;
    padding: 26rpx 0;
    font-size: 32rpx;
    color: #333;
    position: relative;
    &.active {
      color: #e60012;
      font-weight: bold;
      &::after {
        content: '';
        position: absolute;
        left: 50%;
        bottom: 0;
        transform: translateX(-50%);
        width: 40rpx;
        height: 4rpx;
        background: #e60012;
      }
    }
  }
}

/* 日期栏 */
.date-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 32rpx;
  background: #fff;
  .left {
    font-size: 30rpx;
    color: #333;
    font-weight: bold;
  }
  .date {
    font-size: 30rpx;
    color: #333;
  }
  .history-btn {
      margin: 0;
      font-size: 28rpx;      /* 原来是 26rpx */
      color: #e60012;
      border: 1rpx solid #e60012;
      background: transparent;
      border-radius: 8rpx;   /* 原来是 6rpx */
      padding: 4rpx 12rpx;   /* 原来是 4rpx 16rpx */
      line-height: 1.3;      /* 保证垂直居中 */
    }
}

/* 周期栏 */
.period-bar {
  display: flex;
  background: #fff;
  padding: 0 32rpx 20rpx;
  .period {
    margin-right: 32rpx;
    font-size: 28rpx;
    color: #666;
    &.active {
      color: #e60012;
      font-weight: bold;
    }
  }
}

/* 表头 */
.table-header {
  display: flex;
  background: #fafafa;
  border-bottom: 1rpx solid #e8e8e8;
}
.fixed-left-header {
  width: 280rpx;
  flex-shrink: 0;
  border-right: 1rpx solid #e8e8e8;
   justify-content: center;
    text-align: center;
}
.scroll-right-header {
  flex: 1;
  overflow: hidden;
}

/* ===== 内容区 ===== */
.scroll-y-wrapper {
  flex: 1;
  overflow: hidden;
  min-height: 0;
  margin-top: 160px;
}
.table-body {
  display: flex;
}
.fixed-left {
  width: 280rpx;
  flex-shrink: 0;
  background: #fff;
  border-right: 1rpx solid #e8e8e8;
}
.scroll-right-body {
  flex: 1;
  overflow: hidden;
  position: relative;
  /* 偶数行背景整片兜底，避免被裁剪 */
  &::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
	// width: 2000rpx;
    right: 0;
    bottom: 0;
    pointer-events: none;
    z-index: -1;
    /* 1086rpx 与 .table-data 同宽 */
    
    background-image: repeating-linear-gradient(
      to bottom,
      transparent        0,
      transparent        88rpx,      /* 奇数行高 */
      #fef6f6            88rpx,      /* 偶数行底色 */
      #fef6f6            176rpx      /* 88*2 */
    );
  }
}
.table-data {
  // min-width: 1200rpx;
}



/* ===== 通用行/单元格 ===== */
.tr {
  display: flex;
  height: 75rpx;       /* 原来是 88 */
  // height: auto;             /* 让内容撑开 */
  align-items: center;
  border-bottom: 1rpx solid #e8e8e8;
   align-items: stretch;       /* 让 td 撑满行高 */

  &.head {
    background: #fafafa;
    font-weight: bold;
    color: #333;
  }
  &.stripe {
    background: #fef6f6;
  }
  &.total {
    background: #e60012;
    color: #fff;
    font-weight: bold;
  }
}
.tr.stripe {
  border-bottom: 1rpx solid #d8d8d8; // 比 #e8e8e8 深一点
}
.th,
.td {
  padding: 12rpx 8rpx;      /* 留一点内边距 */
  width: 215rpx;
  flex-shrink: 0;
  text-align: center;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-right: 1rpx solid #e8e8e8;
  &:last-child {
    border-right: none;
  }
}
.fixed-left-header .th,
.fixed-left .td {
  width: 70rpx;
  &.city {
    width: 170rpx;
  }
}
.sort-th {
  position: relative;
  .arrows {
    display: inline-flex;
    flex-direction: column;
    margin-left: 6rpx;
    .up,
    .down {
      font-size: 20rpx;
      color: #ccc;
      line-height: 1;
      &.active {
        color: #e60012;
      }
    }
  }
}
.rank-box {
  display: inline-block;
  width: 24rpx;
  height: 48rpx;
  line-height: 48rpx;


  text-align: center;
}
.red-text {
  color: #e60012;
}

/* ===== 日期弹窗 ===== */
.mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.45);
  z-index: 999;
  display: flex;
  align-items: flex-end;
}
.picker-panel {
  width: 100%;
  background: #fff;
  border-top-left-radius: 32rpx;
  border-top-right-radius: 32rpx;
}
.picker-item {
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  font-size: 30rpx;
}
.btn-group {
  display: flex;
  border-top: 1rpx solid #e8e8e8;
  .btn {
    flex: 1;
    text-align: center;
    padding: 28rpx 0;
    font-size: 32rpx;
    color: #666;
    &.confirm {
      color: #e60012;
      font-weight: bold;
    }
  }
}
/* 固定在底部 */
.total-row{
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 100rpx;
  background: #e60012;
  color: #fff;
  font-weight: bold;
  display: flex;
  z-index: 200;
  align-items: stretch;   /* 让子元素高度 100% */

}

/* 左侧固定列，宽度和上面保持一致 280rpx */
.total-left{
  width: 280rpx;
  flex-shrink: 0;
  display: flex;
  border-right: 1rpx solid #fff;
  .td{
    width: 100rpx;
    &:last-child{ width: 170rpx; }
  }
}

/* 右侧滚动区域 */
.total-right{
  flex: 1;
  overflow: hidden;
}
.total-data{
  display: flex;
  min-width: 88rpx;
}
.total-row .td{
  display: flex;
  align-items: center;
  justify-content: center;
  width: 70rpx;
  flex-shrink: 0;
  font-size: 28rpx;
  border-right: 1rpx solid #fff;
  &:last-child{ border-right: none; }
}
.total-row .td-mx {
  padding: 12rpx 8rpx;
  width: 235rpx;
  flex-shrink: 0;
  text-align: center;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-right: 1rpx solid #fff;   /* 与合计行主题色一致 */
  height: 50px;                    /* 关键：占满父级高度 */
  box-sizing: border-box;
  &:last-child {
    border-right: none;
  }
}

/* 给主体区域留一点底边距，避免被合计行遮住 */
.scroll-y-wrapper{
	margin-top: 0;
  padding-bottom: 110rpx;
}
/* 1. 右侧内容一次性做宽 */
// .table-data,
// .total-data {
//   min-width: 1200rpx;
// }

/* 2. 左侧固定列 + 右侧内容行统一背景 */
.fixed-left   .tr:nth-child(odd)  { background: #fff; }
.fixed-left   .tr:nth-child(even) { background: #fef6f6; }

.table-data   .tr:nth-child(odd)  { background: #fff; }
.table-data   .tr:nth-child(even) { background: #fef6f6; }

/* 3. 删除/覆盖之前所有渐变、::after 背景 */
.scroll-right-body::after { display: none; }
.black-text {
  color: #000;
}
/* ========== 禁止页面整体上下滑动 ========== */
page {
  height: 100vh;
  overflow: hidden;   /* 关键：干掉页面级滚动 */
}

/* 让容器高度=屏幕高度，只给表格区域留滚动权限 */
.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 顶部固定区、底部合计行不滚动 */
.fixed-top,
.total-row {
  flex-shrink: 0;
}

/* 中间唯一可滚动区域 */
.scroll-y-wrapper {
  flex: 1;
  overflow-y: auto;   /* 仅这里允许上下滑 */
  overflow-x: hidden;
  -webkit-overflow-scrolling: touch; /* iOS 顺滑 */
}
/* 默认黑色无下划线 */
// .city-text {
//   color: #000;
// }
/* 仅在 county 时红色 + 下划线 */
/* 1. 先保证文字颜色和相对定位（这部分你原有，但可统一格式） */
/* 为jb=1和jb=2添加红色文字和下划线 */
.city-text[jb="1"],
.city-text[jb="2"],
.city-text[jb="3"]{
  color: red !important;
    text-decoration: underline;
    text-underline-offset: 2px;
    cursor: pointer;
    white-space: normal;
    word-break: break-all;
    display: inline-block;
    width: 100%;
    line-height: 1.6;
}







.city-text[jb="4"] {
  color: #000;
  pointer-events: none; /* 禁止点击 */
}
.tr.h80 { min-height: 79rpx; }
.tr.h120 { min-height: 120rpx; }
.tr.h160{ min-height:160rpx; }
.tr.h200{ min-height:200rpx; }
.tr.h240{ min-height:240rpx; }
.tr.h280{ min-height:280rpx; }

</style>